﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Apollo;
using Apollo.Core;

namespace Apollo.Website
{
    public partial class QuickView : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int viewId = 0;
            if (!int.TryParse(Request["ViewId"], out viewId))
            {
                EntityGridView.Visible = false;
                return;
            }

            if (Request["b"] == "n")
                EntityGridView.Behavior = Controls_EntityGridView.EntityGridBehavior.Normal;

            EntityView view = Apollo.Application.Meta<EntityView>()
                .SingleOrDefault<EntityView>(ev => ev.Id == viewId);

            if (view == null)
            {
                EntityGridView.Visible = false;
                return;
            }

            LanguageDefinition ld = Apollo.Application.Meta<LanguageDefinition>()
                   .SingleOrDefault<LanguageDefinition>(l => l.Type == "EntityView"
                       && l.CodeHi == view.Id.ToString()
                       && l.Language.Id == Apollo.Application.CurrentLanguage.Id);

            this.Title = (ld != null ? ld.DisplayName : view.Name) + " [Filtered]";

            EntityGridView.EntityView = view;
            EntityGridView.Columns = Request["c"];
            if (!string.IsNullOrEmpty(this.Request["f"]))
            {
                FilterGroup group = WebHelper.DeserializeGroupFromJSON(
                    this.Request["f"],
                    EntityGridView.EntityView != null ? EntityGridView.EntityView.Entity.MappedClass
                            : EntityGridView.UserView.Entity.MappedClass);

                if (!group.IsEmpty)
                {
                    EntityGridView.FilterString = WebHelper.SerializeGroupToJSON(group);

                    // format it to be used in javascript code
                    EntityGridView.FilterString = EntityGridView.FilterString.Replace("\\", "\\\\").Replace("\"", "\\\"");
                }
            }

            LiteralJS.Text += @"
    <script type=""text/javascript"">
        $(document).ready(function() {
            " + EntityGridView.GetJavaScriptMethodDefinition() + @"
        });
    </script>
";
        }
    }

}